import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../entities/user.entity';
import { UpdateUser } from './dto/updateUser.dto';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
  ) {}

  findAll(search: string) {
    const marker = this.usersRepository
      .createQueryBuilder('user')
      .where('user.eMail LIKE :eMail', { eMail: `%${search}%` })
      .getMany();
    return marker;
  }

  findOne(id: string) {
    return this.usersRepository.findOne({ where: { id } });
  }

  async update(id: string, updateUserDto: UpdateUser) {
    let user: User = await this.findOne(id);
    if (!user) throw new HttpException('该用户不存在', HttpStatus.BAD_REQUEST);
    let reslut = await this.usersRepository.findOne({
      where: { mobile: updateUserDto.mobile },
    });
    if (reslut&&reslut.id!=id) {
      throw new HttpException('该手机号已注册', HttpStatus.BAD_REQUEST);
    }
    reslut = await this.usersRepository.findOne({
      where: { eMail: updateUserDto.eMail },
    });
    if (reslut&&reslut.eMail!=updateUserDto.eMail) {
      throw new HttpException('该邮箱已注册', HttpStatus.BAD_REQUEST);
    }
    Object.assign(user, updateUserDto);
    return this.usersRepository.save(user);
  }

  async remove(id: string) {
    const user: User = await this.findOne(id);
    if (!user) throw new HttpException('该用户不存在', HttpStatus.BAD_REQUEST);
    return this.usersRepository.remove(user);
  }
}
